package at.fhj.itm.model;
/**
 * this class is responsible for data access and business functionalities
 * = Domain- and DataSource-Layer
 */

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Hashtable;

import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreNotOpenException;

import at.fhj.itm.controller.DictControllerV2;

public class Translator 
{
	private RecordStore vocabEntries=null;
	private RecordStore bookmarkStore;
	private Hashtable bookmarks;
	private VocabFilter vocabFilter;
	private VocabComparator vocabComparator;
	private RecordEnumeration recordEnum=null;
	
	public Translator()
	{
		setVocabComparator(new VocabComparator());		
	}
	
	public String lookupMeaning(byte[] vocab)
	{
		return VocabEntry.getAll(vocab);
	}
	
	/**
	 * this method fetches all vocabs matching the given search string
	 * 
	 * @return
	 */
	public RecordEnumeration makeSuggestions(String word)
	{ 
		//determine if new lookup required or already in Collection
		
		//if new search: store data for faster search later on
		
		if(vocabFilter==null)
		{
			if(word==null || word=="")
			{
				vocabFilter = new VocabFilter("a");
			}
			else
			{
				vocabFilter = new VocabFilter(word);
			}
		}
		else
		{
			if(word==null || word=="")
			{
				vocabFilter.setUserInput("a");
			}
			else
			{
				vocabFilter.setUserInput(word);
			}			
		}		
		
		
		try {
//			recordEnum = vocabEntries.enumerateRecords(vocabFilter, vocabComparator, false);
			recordEnum = vocabEntries.enumerateRecords(null, null, false);
		} catch (RecordStoreNotOpenException e) {
			e.printStackTrace();
		}
		
		return recordEnum;
		
		//sorting needed ? no, search only, vocab is already sorted
		//perform sorting operation and search for first matching word, fetch until last matching 
//		vocabEntries = suggestions;
//		binsearch(leftIndex, rightIndex);		
	}
	
	public boolean saveInBookmarks(VocabEntry entry)
	{
		boolean success=false;
		bookmarks.put(entry,entry.toString());
		
		return success;
	}
	
	public VocabFilter getVocabFilter() {
		return vocabFilter;
	}

	public void setVocabFilter(VocabFilter vocabFilter) 
	{
		if(vocabFilter==null)
		{
			throw new IllegalArgumentException();
		}
		this.vocabFilter = vocabFilter;
	}

	public VocabComparator getVocabComparator() {
		return vocabComparator;
	}

	public void setVocabComparator(VocabComparator vocabComparator) 
	{
		if(vocabComparator==null)
		{
			throw new IllegalArgumentException();
		}
		this.vocabComparator = vocabComparator;
	}

	public RecordStore getVocabEntries() {
		return vocabEntries;
	}

	public void setVocabEntries(RecordStore vocabEntries) 
	{
		if(vocabEntries==null)
		{
			throw new IllegalArgumentException();
		}
		this.vocabEntries = vocabEntries;
	}

	public RecordEnumeration getrEnum() {
		return recordEnum;
	}

	public void setrEnum(RecordEnumeration rEnum) {
		if(rEnum==null)
		{
			throw new IllegalArgumentException();
		}
		this.recordEnum = rEnum;
	}
	public void readFromPackagedFile() 
	{
		System.out.println("--------------------------------- start readFromPackagedFile()");
		   try 
		   {
			   InputStream in =this.getClass().getResourceAsStream("/"+DictControllerV2.VOCABFILE_NAME);
			  			   
			   InputStreamReader inr = new InputStreamReader(in, "UTF8");
			   StringBuffer  buffer = new StringBuffer();
			   StringBuffer mainBuffer = new StringBuffer();
			   
			   int charCode;			   
			   int delimiterCounter=0;
			   char ch;	
			   
			   ByteArrayOutputStream baos = new ByteArrayOutputStream();
			   DataOutputStream dos = new DataOutputStream(baos);
			   
			   //write a byte array for a vocab entry for each line of the resource file
			   while( (charCode = inr.read()) > -1)
			   {
				   ch = (char)charCode;
				  
				   if(ch==':')
				   {
					   delimiterCounter++;
					   if(delimiterCounter%2==1)
					   {
						   System.out.println("buffer content: "+buffer.toString());
						   System.out.println("------------------------------- attempting to write german vocab to buffer");
						   mainBuffer.setLength(VocabEntry.STARTPOS_GERMAN);
						   mainBuffer.insert(VocabEntry.STARTPOS_GERMAN, buffer.toString());
						   
//						   while(buffer.length()+VocabEntry.STARTPOS_GERMAN-1<=VocabEntry.ENDPOS_GERMAN)
//						   {
//							   dos.writeUTF("\n");
//						   }
						   buffer.delete(0, buffer.length());
					   }
					   else if(delimiterCounter%2==0)
					   {
						   System.out.println("buffer content: "+buffer.toString());
						   System.out.println("------------------------------- attempting to write arabic vocab to buffer");
						   mainBuffer.setLength(VocabEntry.STARTPOS_ARABIC+1);
						   mainBuffer.insert(VocabEntry.STARTPOS_ARABIC, buffer.toString());
						   buffer.delete(0, buffer.length());
					   }
				   }
				   else if (ch=='\n')
				   {
					   
//					   dos.writeUTF(buffer.toString());
//					   System.out.println("------------------------------- verbal arabic vocab written to buffer");
//					   int verbalLength = VocabEntry.ENDPOS_VERBAL - VocabEntry.STARTPOS_VERBAL + 1;
//					   for(int i=0; i <verbalLength-buffer.toString().length(); i++)
//					   {
//						   dos.writeUTF("\n");
//					   }

					   System.out.println("buffer content: "+buffer.toString());
					   System.out.println("------------------------------- attempting to write verbal arabic vocab to buffer");
					   mainBuffer.setLength(VocabEntry.STARTPOS_VERBAL);
					   mainBuffer.insert(VocabEntry.STARTPOS_VERBAL, buffer.toString());
					   mainBuffer.setLength(VocabEntry.ENDPOS_VERBAL+1);
					   
					   buffer.delete(0, buffer.length());
					   
					   dos.writeUTF(mainBuffer.toString());					   
					   byte[] vocab = baos.toByteArray();
					   System.out.println("--------------- attempting to write record");
					   vocabEntries.addRecord(vocab, 0,vocab.length);
					   mainBuffer.delete(0, mainBuffer.length());					   
				   }
				   else
				   {				   
					   buffer.append(ch);
				   }
			   }
			   System.out.println("---------------------------: RS contains " + vocabEntries.getNumRecords() + "records");
			   System.out.println("--------------------------------- end readFromPackagedFile()");			   
		   }
		   catch(Exception e)
		   {
			   System.out.println("--------------------------------- end with EXCEPTION" + e.getClass().getName()+ " readFromPackagedFile()");	
			   e.printStackTrace();
		   }
	}
		   
			   
//			   //byte Array for holding one line of the vocab file
//			   byte[] vocabEntry= new byte[VocabEntry.ENDPOS_VERBAL+1];
//			   byte[] intermediateByteArray;
//			   
//		       int charCode;
//		       int delimiterCounter=0;
//		       char ch;
//		       while ((charCode = inr.read()) > -1)
//		       {
//		    	 ch = (char)charCode;
//		    	 if(ch=='\n')
//		    	 {
//		    		 delimiterCounter=0;		    		 
//		    		 //write verbal into its fixed place in the record
//		    		 
//		    		 intermediateByteArray = buffer.toString().getBytes("UTF8");
//		    		 int i;
//		    		 for (i=0; i < intermediateByteArray.length; i++)
//	    			 {
//		    			
//	    				 vocabEntry[i+VocabEntry.STARTPOS_VERBAL]=intermediateByteArray[i];
//	    				 System.out.print(vocabEntry[i]);
//	    			 }
//		    		 System.out.println();
//		    		 
////		    		 while (i+VocabEntry.STARTPOS_VERBAL<=VocabEntry.ENDPOS_VERBAL)
////		    		 {		    			 
////		    			 vocabEntry[i]=new String("\r").getBytes("UTF8")[0];
////		    			 i++;
////		    		 }		    		
//		    		 vocabEntries.addRecord(vocabEntry, 0, vocabEntry.length);		    		 
//		    		 buffer.delete(0, buffer.length());
//		    	 }
//		    	 else if(ch==':')
//		    	 {
//		    		 delimiterCounter++;
//		    		 buffer.delete(0, buffer.length());
//		    		 
//		    		 if(delimiterCounter==1)
//		    		 {
//		    			 System.out.println(buffer.toString());
//		    			 intermediateByteArray = buffer.toString().getBytes("UTF8");		    			 
//		    			//write german vocab into it's fixed place in the record
//		    			 int i=0;
//		    			 for (i=0; i < intermediateByteArray.length; i++)
//		    			 {
//		    				 vocabEntry[i+VocabEntry.STARTPOS_GERMAN]=intermediateByteArray[i];		    				
//		    				 System.out.print(vocabEntry[i]);
//		    			 }
//		    			 System.out.println(":");
////		    			 while (i+VocabEntry.STARTPOS_GERMAN<=VocabEntry.ENDPOS_GERMAN)
////			    		 {		    				 
////			    			 vocabEntry[i]=new String("\r").getBytes("UTF8")[0];
////			    			 i++;
////			    		 }		    			 
//		    			 buffer.delete(0, buffer.length());
//		    			 intermediateByteArray = null;
//		    		 }		    		
//		    		 else if(delimiterCounter==2)
//		    		 {
//		    			 buffer.toString();
//		    			 intermediateByteArray = buffer.toString().getBytes("UTF8");
//		    			//write arabic vocab into it's fixed place
//		    			 int i;
//		    			 for (i = 0; i < intermediateByteArray.length; i++)
//		    			 {
//		    				 vocabEntry[i+VocabEntry.STARTPOS_ARABIC]=intermediateByteArray[i];
//		    				 System.out.print(vocabEntry[i]);
//		    			 }
//		    			 System.out.println();
////		    			 while (i+VocabEntry.STARTPOS_ARABIC<=VocabEntry.ENDPOS_ARABIC)
////			    		 {		    			 
////		    				 vocabEntry[i]=new String("\r").getBytes("UTF8")[0];
////			    			 i++;
////			    		 }   		 
////		    			 
//		    			 buffer.delete(0, buffer.length());
//		    			 intermediateByteArray = null;
//		    			 
//		    		 }
//		    	 }
//		    	 else if(ch=='\r')
//		    	 {
//		    		 
//		    	 }
//		    	 else
//		    	 {
//		    		 buffer.append(ch);
//		    	 }
//		       }
//		       if (inr != null) 
//			         inr.close();  		                    
//		     } 
//		     catch (Exception ex) 
//		     {
//		    	 System.out.println(ex.getClass().getName());
//		    	 System.out.println("error reading input file");
//		     }			   
			   
			   //for every line in the vocab file:
			   		//create a record (=byte array), containing german, arabic, verbal
			   			//pick out delimiter between german, arabic, verbal (currently: ":")
			   			//write german into byte array from index GERMAN_STARTPOS to GERMAN_ENDPOS, same with arabic, ...

	
	
//	public String fetchAllBookmarks()
//	{
//	}
//	
//	public String fetchSingleBookmark()
//	{
//		
//	}
	
}
